var icdev = 0; //设备句柄
var lock = new Lock()
var data = undefined
var resetData = undefined
var uid = undefined
var msg = {} ;
var canWrite = false
var layer = layui.layer
var form = layui.form
var staffId = undefined
var status = 0 // 0 未复位   1 已复位
var reader = getReader(async function(){
    // 连接USB读卡器
    try {
        reader.connectUsb(); //连接usb设备
        await lock.wait()
    } catch (e) {
        msg.value = msg.value + e.Message + "\n";
    }
}); //获取reader对象, getReader会自动连接ReaderService服务
if (reader == null) {
    alert('您的浏览器不支持读写器服务.');
}

// 设置回调
reader.onResult(function (ret) {
    data = ret
    console.log("返回："+data.resultData)
    lock.notify(data)
    //执行成功
    if (ret.result == 0) {
        switch (ret.functionId) {
            case READER_CMD._reader_server_connect:
                break;
            case READER_CMD._reader_cmd_connect:
                icdev = parseInt(ret.resultData); //连接成功后, resultData 为设备句柄
                msg.value = msg.value + "读写器连接成功.\n";
                break;
            case READER_CMD._reader_cmd_disconnect:
                msg.value = msg.value + "读写器断开连接成功.\n";
                break;
            case READER_CMD._reader_cmd_beep:
                msg.value = msg.value + "读写器鸣响成功.\n";
                break;
            case READER_CMD._reader_cmd_rf_card:
            case READER_CMD._reader_cmd_rf_card_b:
                msg.value = msg.value + "寻卡成功, 卡片序列号: " + ret.resultData + "\n";
                break;
            case READER_CMD._reader_cmd_c_cpu_reset:
                msg.value = msg.value + "非接触式 TypeA CPU 卡复位成功. 复位信息: " + ret.resultData + "\n";
                break;
            case READER_CMD._reader_cmd_c_cpu_reset_b:
                msg.value = msg.value + "非接触式 TypeB CPU 卡复位成功.\n";
                break;
            case READER_CMD._reader_cmd_rf_halt:
            case READER_CMD._reader_cmd_rf_halt_b:
                msg.value = msg.value + "终止卡片操作成功.\n";
                break;
            case READER_CMD._reader_cmd_uc_auth_key:
                msg.value = msg.value + "Ultralight C 校验密码成功.\n";
                break;
            case READER_CMD._reader_cmd_uev_auth_key:
                msg.value = msg.value + "Ultralight EV 校验密码成功.\n";
                break;
            case READER_CMD._reader_cmd_u_read:
                msg.value = msg.value + "Ultralight / Ultralight C 读数据成功. 读取到的数据: " + ret.resultData + "\n";
                break;
            case READER_CMD._reader_cmd_u_write:
                msg.value = msg.value + "Ultralight / Ultralight C 写数据成功.\n";
                break;
            case READER_CMD._reader_cmd_uc_change_key:
                msg.value = msg.value + "更改  Ultralight C 密码成功.\n";
                break;
        }
    } else {
        //失败打印错误信息
        msg.value = msg.value + ret.resultData + "\n";
    }
    // console.log(data)
});

var can_chongzhi = false
var validateCardMsg = undefined
// 定时寻卡
async function find_card(){
    try {
        reader.rfCard(icdev, 1);
        await lock.wait()
        uid = data.resultData
        console.log(uid)
        if(uid != "请求失败。" && uid != "设备未连接。"){
            clearInterval(timer)
            status = 1
            cardNo = uid
            $("input[name='cardNo']").val(uid)
            $("input[name='cardNo2']").val(uid)
            $.ajax({
                url: HOST+"cz/getStaffInfo?cardNo=" + cardNo
                , beforeSend: function(request) {
                    request.setRequestHeader("token", layui.data('local_store').token);
                }
                , type: "get"
                , async:false
                , success: function (data) {
                    if (data.code == 1){
                        staffId = data.data.staff.id;
                        $("#name").val(data.data.staff.name);
                        // $("#qiye").val(data.data.staff.qiye.qyname);
                        $("#dqtime").val(data.data.staff.dqtime);
                        $("#bh").val(data.data.staff.bh);
                        $("#picture").attr("src" , HOST+"upload/"+data.data.staff.picture)
                        form.render();
                    }else {
                        layer.msg("卡信息不存在！")
                        return;
                    }
                }
            });
            // form.render()
            reader.mifareCpuReset(icdev);
            await lock.wait()
            resetData = data.resultData
            layer.msg("读取中")
            layer.load(2)
            var validateCard = undefined
            $.ajax({
                url:HOST+"card/validateCard?cardNo="+cardNo ,
                beforeSend: function(request) {
                    request.setRequestHeader("token", layui.data('local_store').token);
                },
                async:false ,
                success:function(res) {
                    validateCard = res ;
                }
            })
            console.log(validateCard)
            if(validateCard.code == 200) {
                can_chongzhi = true ;
            }else if(validateCard.code == 500){
                validateCardMsg = validateCard.msg
                $("#msg").html(validateCard.msg)
                form.render()
            }
            await read()
            if(validateCard.code == 501) {
                $("#msg").html(validateCard.msg)
                form.render()
                layer.confirm(validateCard.msg , function(){
                    if(resetData.startsWith("107880B002209000")) {
                        layer.confirm("问题卡，点击确定即可解除绑定关系并且清除卡内信息" , function(idx) {
                            layer.close(idx)
                            $.ajax({
                                url:HOST+"userInfo/bangdin1?cid="+cardNo ,
                                success: function(res) {
                                    console.log(res)
                                    if(res.code == 200) {
                                        // 擦除卡
                                        clearCard2()
                                    }else{
                                        layer.msg(res.msg)
                                    }
                                }
                            })
                        })
                    }else{
                        socket.close()
                        reader.disconnect(icdev);
                        layer.msg("即将进入绑卡界面...")
                        setTimeout(function(){
                            layer.closeAll()
                            layer.open({
                                type:2 ,
                                area:["80%" , "80%"] ,
                                content:"./bangka.html?cid="+uid
                            })
                        } , 500)
                    }
                })
                return ;
            }
            var resultObj = undefined
            $.ajax({
                url:HOST+"userInfo/getStaffByCard?cardNo="+cardNo+"&id="+staffId ,
                beforeSend: function(request) {
                    request.setRequestHeader("token", layui.data('local_store').token);
                },
                async:false ,
                success:function(res){
                    resultObj = res
                }
            })
            if(resultObj.code != 200 && resultObj.msg != "白卡") {
                layer.confirm(resultObj.msg)
                return
            }else if(resultObj.msg == "白卡"){

            }else{
                canWrite = true
            }
        }
    } catch (e) {
        console.log(e)
        // msg.value = msg.value + e.Message + "\n";
    }
}

function Bytes2Str(arr)

{
    var str = "";

    for(var i=0; i<arr.length; i++)

    {
       var tmp = arr[i].toString(16);

       if(tmp.length == 1)

       {
           tmp = "0" + tmp;

       }

       str += tmp;

    }

    return str;

}

function Str2Bytes(str)
 
{
 
    var pos = 0;
 
    var len = str.length;
 
    if(len %2 != 0)
 
    {
 
       return null; 
 
    }
 
    len /= 2;
 
    var hexA = new Array();
 
    for(var i=0; i<len; i++)
 
    {
 
       var s = str.substr(pos, 2);
 
       var v = parseInt(s, 16);
 
       hexA.push(v);
 
       pos += 2;
 
    }
 
    return hexA;
 
}

function UTF8ToStr(arr) {
    let val = ''
    arr.forEach(item => {
        if (item < 127) {
            val += String.fromCharCode(item)
        } else {
            val += '%' + item.toString(16).toUpperCase()
        }
    })
    try {
        return decodeURI(val)
    } catch (err) {
        return val
    }
}

var card_msg = false

timer = setInterval(find_card , 1000)

async function read(){
    // 进入目录
    reader.mifareCpuTransmit(icdev , "00A40000023F00") ;
    await lock.wait()
    if(checkRs() != undefined) {
        layer.closeAll()
        card_msg = true
        layer.prompt({title:"请输入卡片上用户编号", yes:function(index,layero){
            var content = layero.find(".layui-layer-input").val();
            layer.close(index)
            if(content == undefined || content == "") {
                layer.msg("请输入卡片上用户编号")
                return
            }
            socket.close()
            layer.open({
                type:2
                ,title:"会员开卡"
                ,skin:'layui-layer-molv'
                ,area: ['95%', '99%']
                ,content:"../../makeCard/baika_handle.html?name="+content  //js获取url参数
                ,success: function (index, layero) {
                    // 这里是这个弹出层打开完成后所进行的操作
                    // form.ready();
                }
            });
        }} , function(){

        })
        validateCardMsg = undefined
        return false
    }
    reader.mifareCpuTransmit(icdev , "00A40000021001") ;
    await lock.wait()
    if(data.resultData == "6A82") {
        layer.closeAll();
        layer.msg("卡内信息异常,需要重新写卡")
        return
    }
    // 选择文件
    reader.mifareCpuTransmit(icdev , "00A4000002001E") ;
    await lock.wait()
    if(data.resultData == "6A82") {
        layer.closeAll();
        layer.msg("卡内信息异常,需要重新写卡")
        return 
    }
    var info = "" ;
    try{
        for(var i = 0 ; ; i++) {
            console.log("读文件");
            var start = Bytes2Str([i*128]) ;
            var str = start ;
            if(start.length == 1) {
                str = "000" + str ;
            }else if(start.length == 2) {
                str = "00" + str ;
            }else if(start.length == 3) {
                str = "0" + str ;
            }
            var ml = "00B0"+str+"80" ;
            reader.mifareCpuTransmit(icdev , ml) ;
            await lock.wait()
            var res = data.resultData.substr(data.resultData , data.resultData.length - 4)
            var flag = false ;
            var len = res.length ;
            for(var j = 0 ; j < res.length ; j+=2) {
                var byte = res.substr(j , 2)
                if(byte == "0A") {
                    flag = true ;
                    len = j ;
                    break ;
                }
            }
            info = info + res.substr(0 , len) ;
            if(flag) {
                break ;
            }
            if(data.resultData == "6700" || data.resultData == "6B00") {
                break
            }
        }
    }catch(e) {
        console.log(e)
    }
    try{
        var arr = Str2Bytes(info)
        var str = UTF8ToStr(arr)
        console.log(str)
        var array = str.split(",")
        if(str.startsWith("10000")) {
            console.log("data:image/png;base64,"+array[7])
            $("#picture2").attr("src" , "data:image/png;base64,"+array[7])
            $("#bh2").val(array[1])
            $("#name2").val(array[0].substr(5))
            $("#qiye2").val(array[2])
            $("#end_time2").val(array[4])
        }else{
            console.log("data:image/png;base64,"+array[0])
            console.log(array[3])
            $("#picture2").attr("src" , "data:image/png;base64,"+array[0])
            $("#bh2").val(array[2])
            $("#name2").val(array[1])
            $("#qiye2").val(array[3])
            $("#end_time2").val(array[5])
        }
    }catch (e) {
        console.log(e)
    }
    // if($("#bh").val() != $("#bh2").val()) {
    //     layer.confirm("卡内信息与数据库不一致,请联系开发者重新绑定关系")
    // }
    // 测试充值
    if(can_chongzhi) {
        // layer.msg("充值测试")
        // reader.mifareCpuTransmit(icdev, "00A40000023F00");
        // await lock.wait() ;
        // if(checkRs() != undefined) {
        //     layer.closeAll()
        //     layer.confirm(checkRs())
        //     return false
        // }
        // reader.mifareCpuTransmit(icdev, "00A40000021001");
        // await lock.wait() ;
        // if(checkRs() != undefined) {
        //     layer.closeAll()
        //     layer.confirm(checkRs())
        //     return false
        // }
        // reader.mifareCpuTransmit(icdev, "0020000003123456");
        // await lock.wait() ;
        // if(checkRs() != undefined) {
        //     layer.closeAll()
        //     layer.confirm(checkRs())
        //     return false
        // }
        // reader.mifareCpuTransmit(icdev, "805000020B0100000001000000810031");
        // await lock.wait() ;
        // if(checkRs() != undefined) {
        //     layer.closeAll()
        //     layer.confirm(checkRs())
        //     return false
        // }
        // var chongzhi = undefined
        // $.ajax({
        //     url:"/cpu_card/chongzhi_test?info="+data.resultData + "&cid="+uid ,
        //     async:false ,
        //     success:function(res) {
        //         chongzhi = res
        //     }
        // })
        // if(chongzhi == undefined) {
        //     layer.closeAll()
        //     layer.msg("网络异常无法充值")
        //     return
        // }else{
        //     if(chongzhi.code != 200) {
        //         layer.closeAll()
        //         layer.msg(chongzhi.msg)
        //         return
        //     }
        // }
        // reader.mifareCpuTransmit(icdev, chongzhi.data);
        // await lock.wait() ;
        // if(checkRs() != undefined) {
        //     layer.closeAll()
        //     layer.confirm(checkRs())
        //     return false
        // }
        // setTimeout(function(){
        //     lock.notify()
        // } , 600)
        // await lock.wait()
        // layer.msg("消费测试")
        // reader.mifareCpuTransmit(icdev, "00A40000023F00");
        // await lock.wait() ;
        // if(checkRs() != undefined) {
        //     layer.closeAll()
        //     layer.confirm(checkRs())
        //     return false
        // }
        // reader.mifareCpuTransmit(icdev, "00A40000021001");
        // await lock.wait() ;
        // if(checkRs() != undefined) {
        //     layer.closeAll()
        //     layer.confirm(checkRs())
        //     return false
        // }
        // reader.mifareCpuTransmit(icdev, "805001020B0100000001000000810031");
        // await lock.wait() ;
        // if(checkRs() != undefined) {
        //     layer.closeAll()
        //     layer.confirm(checkRs())
        //     return false
        // }
        // var xiaofei = undefined
        // $.ajax({
        //     url:"/cpu_card/xiaofei_test?info="+data.resultData + "&cid="+uid ,
        //     async:false ,
        //     success:function(res) {
        //         xiaofei = res
        //     }
        // })
        // if(xiaofei == undefined) {
        //     layer.closeAll()
        //     layer.msg("网络异常无法充值")
        //     return
        // }else{
        //     if(xiaofei.code != 200) {
        //         layer.closeAll()
        //         layer.msg(xiaofei.msg)
        //         return
        //     }
        // }
        // reader.mifareCpuTransmit(icdev, xiaofei.data);
        // await lock.wait() ;
        // if(checkRs() != undefined) {
        //     layer.closeAll()
        //     layer.confirm(checkRs())
        //     return false
        // }
        // setTimeout(function(){
        //     lock.notify()
        // } , 600)
        // await lock.wait()
    }
    layer.closeAll()
    layer.msg("卡正常")
    console.log(validateCardMsg)
    if(validateCardMsg != undefined) {
        layer.confirm($("#msg").html())
    }
    form.render()
}

// parent.location.reload()

async function write(){
    if(staffId == undefined) {
        layer.msg("卡与用户未绑定")
        return
    }
    if($("#bh").val() != $("#bh2").val()) {
        layer.confirm("卡内信息与数据库不一致,请联系开发者重新绑定关系")
        return
    }
    // 进入mf
    reader.mifareCpuTransmit(icdev, "00A40000023F00");
    await lock.wait() ;
    if(status == 1) {
        var cz2 = $("#cz2").val();
        var index = layer.confirm("确认开卡?,在开卡过程中请勿将卡片拿开" , async function(){
            var index2 = layer.load(1)
            if(resetData.startsWith("107880B002209000")) {
                // 外部认证
                var wbrz = undefined
                reader.mifareCpuTransmit(icdev, "0084000004");
                await lock.wait() ;
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                $.ajax({
                    url:HOST+"cpu_card/certification?cid="+uid+"&random="+data.resultData+"&type=1" ,
                    beforeSend: function(request) {
                        request.setRequestHeader("token", layui.data('local_store').token);
                    },
                    async:false,
                    success:function(res){
                        if (res.code == 200) {
                            wbrz = "0082000008" + res.data
                        }else {
                            wbrz = undefined
                            layer.msg(res.msg);
                        }
                    }
                })
                if(wbrz == undefined) {
                    layer.close(index);
                    layer.close(index2);
                    return
                }
                reader.mifareCpuTransmit(icdev , wbrz) ;
                await lock.wait()
                // 擦除卡信息
                reader.mifareCpuTransmit(icdev , "800E000000") ;
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                // 外部认证
                wbrz = undefined
                reader.mifareCpuTransmit(icdev, "0084000004");
                await lock.wait() ;
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                $.ajax({
                    url:HOST+"cpu_card/certification?cid="+uid+"&random="+data.resultData+"&type=3" ,
                    beforeSend: function(request) {
                        request.setRequestHeader("token", layui.data('local_store').token);
                    },
                    async:false,
                    success:function(res){
                        if (res.code == 200) {
                            wbrz = "0082000008" + res.data
                        }else {
                            wbrz = undefined
                            layer.msg(res.msg);
                        }
                    }
                })
                if(wbrz == undefined) {
                    layer.close(index);
                    layer.close(index2);
                    return
                }
                reader.mifareCpuTransmit(icdev , wbrz) ;
                await lock.wait()
                /*if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }*/

                // 请求开卡指令
                //var uuID = $("#kk").val();
                $.ajax({
                    url:HOST+"cpu_card/writeFaildCard?type=1&cid=" + uid + "&uid=" + staffId + "&ast=" + resetData + "&random="  ,
                    async:false ,
                    success:function(res) {
                        if(res.code == 200) {
                            result = res.data
                        }else{
                            layer.msg(res.msg);

                            result = undefined
                        }
                    }
                })

                if(result == undefined) {
                    layer.close(index);
                    layer.close(index2);
                    return
                }

                // 擦除卡信息
                reader.mifareCpuTransmit(icdev , "800E000000") ;
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 建立key文件
                reader.mifareCpuTransmit(icdev , "80E00000073F00C001FAFFFF")
                await lock.wait() ;
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 设置钱包主控秘钥
                reader.mifareCpuTransmit(icdev , result.qb) ;
                await lock.wait() ;
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 设置应用主控秘钥
                reader.mifareCpuTransmit(icdev , result.root) ;
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 创建目录
                reader.mifareCpuTransmit(icdev , "80E01001113821B6F0F095FFFFA00000000386980701")
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 进入目录
                reader.mifareCpuTransmit(icdev , "00A4040009A00000000386980701")
                await lock.wait() ;
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 创建秘钥文件
                reader.mifareCpuTransmit(icdev , "80E00000073F024101FADFDA")
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 设置钱包主控秘钥 目录下
                reader.mifareCpuTransmit(icdev , result.dir_qb)
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 设置目录秘钥
                reader.mifareCpuTransmit(icdev , result.dir)
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 设置pin
                reader.mifareCpuTransmit(icdev , result.pin) ;
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 消费秘钥
                reader.mifareCpuTransmit(icdev , result.xf)
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 设置圈存秘钥
                reader.mifareCpuTransmit(icdev , result.qc)
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 设置tac秘钥
                reader.mifareCpuTransmit(icdev , result.tac)
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 创建文件
                reader.mifareCpuTransmit(icdev , result.file)
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 选择文件
                reader.mifareCpuTransmit(icdev , result.select_file)
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 写文件
                for(var i in result.write_file) {
                    reader.mifareCpuTransmit(icdev , result.write_file[i])
                    await lock.wait()
                    if(checkRs() != undefined) {
                        layer.closeAll()
                        layer.msg(checkRs())
                        return
                    }
                }
                layer.msg("开卡成功")
                reader.rfHalt(icdev);
                setTimeout(function(){
                    layer.closeAll() ;
                    parent.location.reload()
                } , 1000)
            }else {
                // 获取随机数
                var result = undefined
                reader.mifareCpuTransmit(icdev, "0084000004");
                await lock.wait();
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.confirm(checkRs())
                    return false
                }

                //  测试
                $.ajax({
                    url: HOST+"cpu_card/certification?cid=" + uid + "&random=" + data.resultData + "&type=1",
                    beforeSend: function(request) {
                        request.setRequestHeader("token", layui.data('local_store').token);
                    },
                    async: false,
                    success: function (res) {
                        result = "0082000008" + res.data
                    }
                })
                if (result == undefined) {
                    layer.msg("网络异常,无法完成开卡")
                    return
                }
                reader.mifareCpuTransmit(icdev, result);
                await lock.wait()

                reader.mifareCpuTransmit(icdev, "0084000004");
                await lock.wait();
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.confirm(checkRs())
                    return false
                }
                //  测试

                // 请求开卡指令
                result = undefined
                a = undefined
                $.ajax({
                    url: HOST+"cpu_card/writeFaildCard?type=0&cid=" + uid + "&uid=" + staffId + "&ast=" + resetData + "&random=" + data.resultData,
                    async: false,
                    success: function (res) {
                        if (res.code == 200) {
                            result = res.data
                        } else {
                            a = res.msg
                        }
                    }
                })
                if (result == undefined) {
                    layer.closeAll()
                    layer.msg(a)
                    return
                }

                // 测试
                console.log(result)
                // 清除卡原本目录结构
                reader.mifareCpuTransmit(icdev, result.clear_card);
                await lock.wait();
                if (checkRs() != undefined) {
                    layer.confirm(checkRs())
                    return
                }
                // 测试

                // // 创建mf
                // reader.mifareCpuTransmit(icdev, result.kaika);
                // await lock.wait() ;
                // if(checkRs() != undefined) {
                //     layer.closeAll()
                //     layer.msg(checkRs())
                //     return
                // }
                // 外部认证
                var wbrz = undefined
                reader.mifareCpuTransmit(icdev, "0084000004");
                await lock.wait();
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.confirm(checkRs())
                    return
                }
                $.ajax({
                    url: HOST+"cpu_card/certification?cid=" + uid + "&random=" + data.resultData + "&type=1",
                    beforeSend: function(request) {
                        request.setRequestHeader("token", layui.data('local_store').token);
                    },
                    async: false,
                    success: function (res) {
                        wbrz = "0082000008" + res.data
                    }
                })
                if (result == undefined) {
                    layer.closeAll()
                    layer.msg("网络异常,无法完成开卡")
                    return
                }
                reader.mifareCpuTransmit(icdev, wbrz);
                await lock.wait()
                // 设置根目录密钥
                // reader.mifareCpuTransmit(icdev, result.root);
                // await lock.wait()
                // if(checkRs() != undefined) {
                //     layer.closeAll()
                //     layer.msg(checkRs())
                //     return
                // }
                // 创建文件夹
                await create_dir(result.create_dir)
                reader.mifareCpuTransmit(icdev, "00A40000021001");  // 进入目录
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.confirm(checkRs())
                    return
                }
                // 目录外部认证
                reader.mifareCpuTransmit(icdev, "0084000004");
                await lock.wait();
                $.ajax({
                    url: HOST+"cpu_card/certification?cid=" + uid + "&random=" + data.resultData + "&type=2",
                    beforeSend: function(request) {
                        request.setRequestHeader("token", layui.data('local_store').token);
                    },
                    async: false,
                    success: function (res) {
                        wbrz = "0082000008" + res.data
                    }
                })
                reader.mifareCpuTransmit(icdev, wbrz);
                await lock.wait()
                // 设置目录密钥
                reader.mifareCpuTransmit(icdev, result.dir);
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.confirm(checkRs())
                    return
                }
                // 设置消费密钥
                reader.mifareCpuTransmit(icdev, result.xf);
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.confirm(checkRs())
                    return
                }
                // 5.设置圈存密钥
                reader.mifareCpuTransmit(icdev, result.qc);
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.confirm(checkRs())
                    return
                }
                // 6.设置TAC密钥
                reader.mifareCpuTransmit(icdev, result.tac);
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.confirm(checkRs())
                    return
                }
                // 7.设置PIN密码
                reader.mifareCpuTransmit(icdev, result.pin);
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.confirm(checkRs())
                    return
                }
                // 进入目录
                reader.mifareCpuTransmit(icdev, "00A40000021001");  // 进入目录
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.confirm(checkRs())
                    return
                }
                // 目录外部认证
                reader.mifareCpuTransmit(icdev, "0084000004");
                await lock.wait();
                $.ajax({
                    url: HOST+"cpu_card/certification?cid=" + uid + "&random=" + data.resultData + "&type=2",
                    beforeSend: function(request) {
                        request.setRequestHeader("token", layui.data('local_store').token);
                    },
                    async: false,
                    success: function (res) {
                        wbrz = "0082000008" + res.data
                    }
                })
                reader.mifareCpuTransmit(icdev, wbrz);
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.confirm(checkRs())
                    return
                }
                for (var i in result.createFiles) {
                    // 8.创建文件
                    reader.mifareCpuTransmit(icdev, result.createFiles[i])
                    await lock.wait()
                    if (checkRs() != undefined) {
                        layer.closeAll()
                        layer.confirm(checkRs())
                        return
                    }
                }
                // 写文件
                reader.mifareCpuTransmit(icdev, result.select_file);
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.confirm(checkRs())
                    return
                }
                for (var i in result.write_file) {
                    reader.mifareCpuTransmit(icdev, result.write_file[i])
                    await lock.wait()
                    if (checkRs() != undefined) {
                        layer.closeAll()
                        layer.confirm(checkRs())
                        return
                    }
                }

                layer.msg("写卡成功")
                reader.rfHalt(icdev);
                setTimeout(function () {
                    location.reload()
                }, 300)
                // 获取随机数
            }
        })
    }else{
        layer.msg("未识别到卡,请重新放置")
    }
}

async function clearCard(){
    // 弹窗提醒
    var index = layer.confirm('擦除卡后，将会解除卡与会员绑定关系，且卡内信息将被清除变为白卡，请谨慎操作！', async  function (index) {
        if(resetData.startsWith("107880B002209000")) {
            clearCard1()
        }else {
            layer.msg("该卡不支持擦除卡");
        }
    })
}

async function clearCard1(){
    // 外部认证
    var wbrz = undefined

    reader.mifareCpuTransmit(icdev, "00A40000023F00");
    await lock.wait()
    if(checkRs() != undefined) {
        layer.closeAll()
        layer.msg(checkRs())
        return false;
    }

    reader.mifareCpuTransmit(icdev, "0084000004");
    await lock.wait();
    if (checkRs() != undefined) {
        layer.closeAll()
        layer.msg(checkRs())
        return
    }
    $.ajax({
        url: HOST+"cpu_card/certification?cid=" + uid + "&random=" + data.resultData + "&type=1",
        beforeSend: function(request) {
            request.setRequestHeader("token", layui.data('local_store').token);
        },
        async: false,
        success: function (res) {
            if (res.code == 200) {
                wbrz = "0082000008" + res.data
            } else {
                wbrz = undefined
                layer.msg(res.msg);
            }
        }
    })
    if (wbrz == undefined) {
        layer.close(index);
        return
    }
    reader.mifareCpuTransmit(icdev, wbrz);
    await lock.wait()
    if (checkRs() != undefined) {
        layer.closeAll()
        layer.msg(checkRs())
        return
    }
    // 擦除卡信息
    reader.mifareCpuTransmit(icdev, "800E000000");
    await lock.wait()
    if (checkRs() != undefined) {
        layer.closeAll()
        layer.msg(checkRs())
        return
    }


    // 请求接口解除卡与用户绑定关系
    $.ajax({
        url: HOST+"cpu_card/clearNewCard?cardNo=" + uid
        , type: "GET"
        , beforeSend: function(request) {
            request.setRequestHeader("token", layui.data('local_store').token);
        }
        , dataType: "json"
        , success: function (data) {
            if (data.code == 200) {
                layer.msg("擦除卡成功！");
                reader.rfHalt(icdev);
                setTimeout(function(){
                    layer.closeAll() ;
                    location.reload()
                } , 1000)
            } else if (data.code == 500) {
                layer.msg(data.msg);
            }else {
                layer.msg("拒绝访问");
            }
        }
        , error: function () {
            console.log("ajax error");
        }
    });
}

async function clearCard2(){
    // 外部认证
    var wbrz = undefined

    reader.mifareCpuTransmit(icdev, "00A40000023F00");
    await lock.wait()
    if(checkRs() != undefined) {
        layer.closeAll()
        layer.msg(checkRs())
        return false;
    }

    reader.mifareCpuTransmit(icdev, "0084000004");
    await lock.wait();
    if (checkRs() != undefined) {
        layer.closeAll()
        layer.msg(checkRs())
        return
    }
    $.ajax({
        url: HOST+"cpu_card/certification?cid=" + uid + "&random=" + data.resultData + "&type=1",
        beforeSend: function(request) {
            request.setRequestHeader("token", layui.data('local_store').token);
        },
        async: false,
        success: function (res) {
            if (res.code == 200) {
                wbrz = "0082000008" + res.data
            } else {
                wbrz = undefined
                layer.msg(res.msg);
            }
        }
    })
    if (wbrz == undefined) {
        layer.close(index);
        return
    }
    reader.mifareCpuTransmit(icdev, wbrz);
    await lock.wait()
    if (checkRs() != undefined) {
        layer.closeAll()
        layer.msg(checkRs())
        return
    }
    // 擦除卡信息
    reader.mifareCpuTransmit(icdev, "800E000000");
    await lock.wait()
    if (checkRs() != undefined) {
        layer.closeAll()
        layer.msg(checkRs())
        return
    }


    // 请求接口解除卡与用户绑定关系
    $.ajax({
        url: HOST+"cpu_card/clearNewCard1?cardNo=" + uid
        , type: "GET"
        , dataType: "json"
        , success: function (data) {
            if (data.code == 200) {
                layer.msg("卡修复成功，请进入开卡界面重新开卡")
                reader.rfHalt(icdev);
                setTimeout(function(){
                    layer.closeAll() ;
                    location.reload()
                } , 1000)
            } else if (data.code == 500) {
                layer.msg(data.msg);
            }else {
                layer.msg("拒绝访问");
            }
        }
        , error: function () {
            console.log("ajax error");
        }
    });
}

// parent.location.reload()

// 创建目录
async function create_dir(str){
    try {
        // 进入根目录
        reader.mifareCpuTransmit(icdev, "00A40000023F00");
        await lock.wait()
        // 外部认证
        var wbrz = undefined
        reader.mifareCpuTransmit(icdev, "0084000004");
        await lock.wait() ;
        if(checkRs() != undefined) {
            layer.confirm(checkRs())
            return
        }
        $.ajax({
            url:HOST+"cpu_card/certification?cid="+uid+"&random="+data.resultData+"&type=1" ,
            beforeSend: function(request) {
                request.setRequestHeader("token", layui.data('local_store').token);
            },
            async:false ,
            success:function(res){
                wbrz = "0082000008" + res.data
            }
        })
        if(wbrz == undefined) {
            layer.msg("网络异常,无法完成开卡")
            return
        }
        reader.mifareCpuTransmit(icdev , wbrz) ;
        await lock.wait()
        // 1.进入目录
        reader.mifareCpuTransmit(icdev, "00A40000021001");
        await lock.wait()
        if(data.resultData == "6A82") {
            // 建立目录
            reader.mifareCpuTransmit(icdev, str);
            await lock.wait()
        }
        // else{
        //     alert("目录已经存在")
        // }
    } catch (e) {
        msg.value = msg.value + e.Message + "\n";
    }
}


function checkRs(){
    switch(data.resultData) {
        case "6200":
            return "警告 信息未提供"
        case "6281":
            return "警告 回送数据可能"
        case "6282":
            return "警告 文件长度小于Le"
        case "6283" :
            return "警告 选中的文件无效"
        case "6284":
            return "警告 FCI格式与P2指定的不符"
        case "6300":
            return "警告 鉴别失败"
        case "63C2":
            return "警告 校验失败（允许重试次数2）"
        case "63C1":
            return "警告 校验失败（允许重试次数1）"
        case "6400":
            return "状态标志位没有变"
        case "6581":
            return "内存失败"
        case "6700":
            return "长度错误"
        case "6882" :
            return "不支持安全报文"
        case "6981":
            return "命令与文件结构不相容，当前文件非所需文件"
        case "6982":
            return "操作条件（AC）不满足，没有校验PIN"
        case "6983":
            return "您的卡已被锁定"
        case "6984":
            return "随机数无效，引用的数据无效"
        case "6985":
            return "使用条件不满足"
        case "6986":
            return "不满足命令执行条件（不允许的命令，INS有错）"
        case "6987":
            return "MAC丢失"
        case "6988":
            return "MAC不正确"
        case "698D":
            return "保留"
        case "6A80":
            return "数据域参数不正确"
        case "6A81":
            return "功能不支持；创建不允许；目录无效；应用锁定"
        case "6A82":
            return "该文件未找到"
        case "6A83":
            return "该记录未找到"
        case "6A84":
            return "文件预留空间不足"
        case "6A86":
            return "P1或P2不正确"
        case "6A88":
            return "引用数据未找到"
        case "6B00":
            return "参数错误"
        case "6C":
            return "Le长度错误"
        case "6E00":
            return "不支持的类：CLA有错"
        case "6F00":
            return "数据无效"
        case "6F01" :
            return "连接中断"
        case "6D00":
            return "不支持的指令代码"
        case "9301":
            return "您的卡余额不足"
        case "9302":
            return "MAC2错误"
        case "9303":
            return "应用被永久锁定"
        case "9401":
            return "您的卡余额不足"
        case "9402":
            return "交易计数器达到最大值"
        case "9403":
            return "密钥索引不支持"
        case "9406":
            return "所需MAC不可用"
        case "6900":
            return "不能处理"
        case "6901":
            return "命令不接受（无效状态）"
        case "61":
            return "正常 需发GET RESPONSE命令"
        case "6600":
            return  "接收通讯超时"
        case "6601":
            return "接收字符奇偶错"
        case "6602":
            return "校验和不对"
        case "6603":
            return "警告 当前DF文件无FCI"
        case "6604":
            return "警告 当前DF下无SF或KF"
        case "6E81":
            return "卡片已离开"
        default:
            return undefined
    }
}